<?php

namespace app\admin\controller;

use app\admin\controller\Admin;
use think\Db;
use think\Hook;

/**
 * @title 库存管理
 */
class Inventory extends Admin {

    /**
     * @title 入库
     */
    public function storage() {

        if (request()->isPost()) {

            $product_id = request()->post('product_id');

            // 仓库列表 
            $warehouse = model('product_warehouse')->model_where()->where('pwu.u_id', UID)->select();

            // 产品信息
            $product = Db::name('product')->where('id', $product_id)->find();


            return $this->renderSuccess('', '', compact('warehouse', 'product'));
        }

        return view();
    }

    /**
     * @title 入库提交  
     */
    public function storage_submit() {

        if (request()->isPost()) {
            $post = request()->post();

            //产品
            $product_ids = isset($post['product_ids']) ? $post['product_ids'] : [];
            $product_ids = array_filter($product_ids);
            //数量
            $quantity = isset($post['quantity']) ? $post['quantity'] : [];
            //仓库
            $warehouse = isset($post['warehouse']) ? $post['warehouse'] : [];
            //价格
            $group_price = isset($post['group_price']) ? $post['group_price'] : [];

            $quantity_total = 0;
            $amount = 0;
            $products = [];



            foreach ($product_ids as $key => $product_id) {

                if (empty($warehouse[$key]))
                    return $this->renderError('请选择仓库');

                if (empty($quantity[$key]) || !preg_match("/^[1-9][0-9]*$/", $quantity[$key]))
                    return $this->renderError('数量有误');

                if (!is_numeric($group_price[$key]))
                    return $this->renderError('金额有误');

                if (!empty($product_id) && is_numeric($product_id) && ($one = Db::name('product')->where('id', $product_id)->find())) {

                    // 放到哪个仓库
                    $one['warehouse'] = $warehouse[$key];
                    // 放了多少数量 
                    $one['quantity'] = $quantity[$key];
                    // 放入的金额是多少
                    $one['group_price'] = $group_price[$key];

                    // 订单数量
                    $quantity_total += $quantity[$key];
                    // 订单总额
                    $amount += $quantity[$key] * $group_price[$key];

                    $products[] = $one;
                }
            }

            if (empty($products))
                return $this->renderError('请选择入库产品');


            // 订单数量 和 订单总额
            $post['quantity'] = $quantity_total;
            $post['amount'] = is_numeric($post['amount']) ? $post['amount'] : 0;

            // 总金额校验
            if ($post['amount'] != $amount) {
                return $this->renderError('总金额有误，请修正后重新提交');
            }


            // dd($products);


            model('product_storage_order')->storage_submit($post, $products);
            if (model('product_storage_order')->hasError()) {
                model('operate')->success(model('product_storage_order')->getError());
                return $this->renderError(model('product_storage_order')->getError());
            }

            model('operate')->success('入库成功');
            return $this->renderSuccess('入库成功', 'reload');
        }
    }

    /**
     * @title 入库撤消
     */
    public function storage_undo($id) {

        empty($id) && exit();

        model('product_storage_order')->storage_undo($id);
        if (model('product_storage_order')->hasError()) {
            model('operate')->failure('入库撤消', UID, model('product_storage_order')->getError());
            return $this->renderError(model('product_storage_order')->getError());
        }

        // 删除采购入库关系表
        $params = ['type' => 'rel_purchase_storage_remove', 'storage_id' => $id];
        Hook::exec('app\\admin\\behavior\\Common', 'run', $params);

        model('operate')->success('入库撤消');
        return $this->renderSuccess('入库撤消成功', 'reload');
    }

    /**
     * @title 入库查询
     */
    public function storage_query() {

        if (!isset($_GET['timea']))
            $_GET['timea'] = date('Y-m-d', strtotime("-30 day"));
        if (!isset($_GET['timeb']))
            $_GET['timeb'] = date('Y-m-d');

        $this->assign('warehouse', model('product_warehouse')->model_where()->where('pwu.u_id', UID)->column('a.id,a.name'));
        $this->assign('category', model('product_category')->lists_select_tree());

        $chart = request()->get('chart');
        $this->assign('chart', $chart);

        //如果export这个参数=1，则直接进行数据导出
        $export = input('get.export', 0);
        if ($export) {
            $lists = model('product_storage_order')->model_where()->group('a.id')->select();
            model('excel')->product_storage_query_export($lists);
            exit();
        }

        if (empty($chart)) {

            $count = model('product_storage_order')->model_where()->count('distinct a.id');
            $lists = model('product_storage_order')->model_where()->group('a.id')->paginate(input('get.page_size', 10), $count, ['query' => request()->get()]);

            $this->assign('count', $count);
            $this->assign('lists', $lists);
            $this->assign('pages', $lists->render());
        } else {

            $count_sum = model('product_storage_order_data')->model_where()->sum('a.quantity');
            $this->assign('count_sum', $count_sum);

            $count = model('product_storage_order_data')->model_where()->count();
            $lists = model('product_storage_order_data')->model_where()->paginate(input('get.page_size', 10), $count, ['query' => request()->get()]);

            $this->assign('count', $count);
            $this->assign('lists', $lists);
            $this->assign('pages', $lists->render());
        }


        return view();
    }

    /**
     * @title 出库
     * 
     */
    public function sales() {



        if (request()->isPost()) {


            $post = request()->post();


            $member_id = request()->post('member_id');

            $product_id = input('post.product_id', 0);



            $member = [];
            if ($member_id) {

                $member = Db::name('member')->alias('a')->join('member_group c', 'a.g_id=c.id', 'LEFT')
                        ->where('a.id', $member_id)
                        ->find();
            }





            $product = [];

            if ($product_id && $product = Db::name('product')->where('id', $product_id)->find()) {

                // 库存大于0的仓库属于自己的找出来
                $product['warehouse'] = Db::name('product_inventory a')
                        ->join('product_warehouse pw', 'pw.id=a.w_id', 'LEFT')
                        ->join('product_warehouse_user pws', 'pws.w_id=a.w_id', 'LEFT')
                        ->where('pws.u_id', UID)
                        ->where('a.p_id', $product_id)
                        ->where('a.quantity', '>', 0)
                        ->field('a.w_id as id,pw.name,a.quantity,pw.default')
                        ->select();

                //如果存在这个值的话，把会员所相关联的分级价格(group_price)找出来 
                if (is_numeric($member_id) && !empty($member_id)) {
                    $group_price = Db::name('member_price')->where('p_id', $product_id)->where('g_id', $member['g_id'])->find();
                    if ($group_price)
                        $product['group_price'] = $group_price['price'];
                }
            }



            return $this->renderSuccess('', '', compact('member', 'product'));

            //   if (!empty($products))
            //       $this->assign('products', $products);
        }


        $this->assign('express', Db::name('express')->order('sort')->select());

        return view();
    }

    /**
     * @title 出库提交
     *     
     */
    public function sales_submit() {

        if (request()->isPost()) {
            $post = request()->post();

            // 产品
            $product_ids = isset($post['product_ids']) ? $post['product_ids'] : [];
            $product_ids = array_filter($product_ids);
            // 仓库
            $product_warehouse = isset($post['product_warehouse']) ? $post['product_warehouse'] : [];
            // 数量 
            $product_quantity = isset($post['product_quantity']) ? $post['product_quantity'] : [];
            // 价格
            $group_price = isset($post['group_price']) ? $post['group_price'] : [];
            // 每个产品的备注
            $remarks = isset($post['remarks']) ? $post['remarks'] : '';

            $amount = 0; // 销售价合计
            $cost = 0; // 成本价合计
            $products = [];
            foreach ($product_ids as $key => $product_id) {

                if (!is_numeric($group_price[$key]) && $group_price[$key] > 0)
                    return $this->renderError('价格有误');

                if (empty($product_quantity[$key]) || !preg_match("/^[1-9][0-9]*$/", $product_quantity[$key]))
                    return $this->renderError('数量有误');

                if (!empty($product_id) && is_numeric($product_id) && ($product = Db::name('product')->where('id', $product_id)->find())) {

                    //上面的三个参数都检查过了，仓库有没有库存也要检查一下。
                    if (!model('product_inventory')->check_product_sales($product['id'], $product_warehouse[$key], $product_quantity[$key]))
                        return $this->renderError('产品：【' . $product['name'] . '】当前库存不足，不能出库，请更换仓库');

                    $product['product_warehouse'] = $product_warehouse[$key];
                    $product['product_quantity'] = $product_quantity[$key];
                    $product['group_price'] = $group_price[$key];
                    $product['remarks'] = $remarks[$key];

                    // 销售总价
                    $amount += sprintf("%.2f", ($product['group_price'] * $product['product_quantity']));
                    // 成本总价
                    $cost += sprintf("%.2f", ($product['purchase'] * $product['product_quantity']));

                    $products[] = $product;
                }
            }

            if (empty($products))
                return $this->renderError('至少提供一个产品');

            $post['amount'] = is_numeric($post['amount']) ? $post['amount'] : 0;
            $post['cost'] = $cost;

            // 总金额校验
            if ($post['amount'] != $amount) {
                return $this->renderError('总金额有误，请修正后重新提交');
            }

            //  dd($products);


            model('product_sales_order')->sales_submit($post, $products);

            if (model('product_sales_order')->hasError()) {
                model('operate')->failure('产品销售', UID, model('product_sales_order')->getError());
                return $this->renderError(model('product_sales_order')->getError());
            }

            model('operate')->success('销售产品');
            return $this->renderSuccess('出库成功', 'reload');
        }
    }

    /**
     * @title 出库查询
     */
    public function sales_query() {

        if (!isset($_GET['timea']))
            $_GET['timea'] = date('Y-m-d', strtotime("-30 day"));
        if (!isset($_GET['timeb']))
            $_GET['timeb'] = date('Y-m-d');

        $this->assign('warehouse', model('product_warehouse')->model_where()->where('pwu.u_id', UID)->column('a.id,a.name'));
        $this->assign('category', model('product_category')->lists_select_tree());


        $chart = request()->get('chart');
        $this->assign('chart', $chart);


        //如果export这个参数=1，则直接进行数据导出
        $export = input('get.export', 0);
        if ($export) {
            $lists = model('product_sales_order')->model_where()->group('a.id')->select();
            model('excel')->product_sales_query_export($lists);
            exit();
        }

        if (empty($chart)) {

            $count = model('product_sales_order')->model_where()->count('distinct a.id');
            $lists = model('product_sales_order')->model_where()->group('a.id')->paginate(input('get.page_size', 10), $count, ['query' => request()->get()]);

            $this->assign('count', $count);
            $this->assign('lists', $lists);
            $this->assign('pages', $lists->render());
        } else {


            $this->assign('count_sum', $count_sum = model('product_sales_order_data')->model_where()->sum('a.quantity'));

            $this->assign('count', $count = model('product_sales_order_data')->model_where()->count());
            $this->assign('lists', $lists = model('product_sales_order_data')->model_where()->paginate(input('get.page_size', 10), $count, ['query' => request()->get()]));
            $this->assign('pages', $lists->render());
        }


        return view();
    }

    /**
     * @title 产品出库撤消
     */
    public function sales_undo($id) {

        empty($id) && exit();

        model('product_sales_order')->sales_undo($id);

        if (model('product_storage_order')->hasError()) {
            model('operate')->failure('出库撤消', UID, model('product_storage_order')->getError());
            return $this->renderError(model('product_storage_order')->getError());
        }
        model('operate')->success('出库撤消成功');
        return $this->renderSuccess('出库撤消成功', 'reload');
    }

    /**
     * @title 退货查询
     */
    public function sales_returns_query() {


        if (!isset($_GET['timea']))
            $_GET['timea'] = date('Y-m-d', strtotime("-30 day"));
        if (!isset($_GET['timeb']))
            $_GET['timeb'] = date('Y-m-d');


        $count = model('product_sales_return')->model_where()->group('a.id')->count();
        $lists = model('product_sales_return')->model_where()->group('a.id')->paginate(input('get.page_size', 10), $count, ['query' => request()->get()]);

        $this->assign('count', $count);
        $this->assign('lists', $lists);
        $this->assign('pages', $lists->render());


        return view();
    }

    /**
     * @title 出库退货提交
     */
    public function sales_returns_add($id) {

        empty($id) && exit();

        if (request()->isPost()) {

            $post = request()->post();


            if (empty($post['warehouse']))
                return $this->renderError('请选择仓库');
            if (empty($post['quantity']) || !is_numeric($post['quantity']))
                return $this->renderError('请确定退货数量');


            $one = model('product_sales_order_data')->get_order_data($id);


            if ($one['returns'] >= $one['quantity'])
                return $this->renderError('该产品已经完全退货');

            $quantity = $one['quantity'] - $one['returns'];
            if (empty($one['quantity']) || $quantity < $post['quantity'])
                return $this->renderError('退货数量不能大与' . $quantity);


            model('product_sales_order_data')->sales_returns_add($post, $one);
            if (model('product_sales_order_data')->hasError()) {
                return $this->renderError(model('product_sales_order_data')->getError());
            }
            return $this->renderSuccess('');
        }


        $this->assign('one', $one = model('product_sales_order_data')->get_order_data($id));

        $this->assign('warehouse', model('product_warehouse')->model_where()->where('pwu.u_id', UID)->select());

        return view();
    }

    /**
     * @title 产品出库查询
     */
    public function sales_look($id) {

        empty($id) && exit();

        $one = model('product_sales_order')->model_where()->where('a.id', $id)->group('a.id')->find();
        $this->assign('one', $one);

        if (empty($one['id']))
            return model('common')->failure('查询到产品出库记录不存在');


        // 快递公司下拉
        $this->assign('express_lists', Db::name('express')->order('sort')->select());

        return view();
    }

    /**
     * @title 补充快递信息
     */
    public function sales_look_info_update($id) {

        empty($id) && exit();

        $post = request()->post();

        model('product_sales_order')->where('id', $id)->update($post);
        if (model('product_sales_order')->hasError()) {
            return $this->renderError(model('product_sales_order')->getError());
        }
        return $this->renderSuccess('更新成功');
    }

    /**
     * @title 库存记录删除
     * 
     */
    public function stock_delete($id) {

        empty($id) && exit();

        $quantity = Db::name('product_inventory')->where('id', $id)->value('quantity');
        if ($quantity) {
            return $this->renderError('还有库存，没法删');
        }

        $affect_rows = Db::name('product_inventory')->where('id', $id)->delete();

        if ($affect_rows) {
            return $this->renderSuccess('', 'reload');
        } else {
            return $this->renderError('删除失败');
        }
    }

    /**
     * @title 库存查询
     */
    public function stock_query() {

        $this->assign('warehouse', model('product_warehouse')->model_where()->where('pwu.u_id', UID)->column('a.id,a.name'));
        $this->assign('category', model('product_category')->lists_select_tree());

        //如果export这个参数=1，则直接进行数据导出
        $export = input('get.export', 0);
        if ($export) {
            $lists = model('product_inventory')->model_where()->group('a.id')->select();
            model('excel')->product_stock_query_export($lists);
            exit();
        }

        $this->assign('count', $count = model('product_inventory')->model_where()->count('distinct a.id'));
        $this->assign('lists', $lists = model('product_inventory')->model_where()->group('a.id')->paginate(input('get.page_size', 10), $count, ['query' => request()->get()]));
        $this->assign('pages', $lists->render());

        return view();
    }

    /**
     * @title 库存调拨窗口
     */
    public function transfer_add($id) {

        empty($id) && exit();


        if (request()->isPost()) {

            $post = request()->post();




            if (empty($post['warehouse']) || !is_numeric($post['warehouse']))
                return $this->renderError('请选择拨出仓库');
            if (empty($post['number']) || !is_numeric($post['number']))
                return $this->renderError('请输入拨出数目');


            // 当前库存表
            $one = model('product_inventory')->where('id', $id)->find();
            if (empty($one) || $one['quantity'] < $post['number']) {
                return $this->renderError('没这么多货');
            }


            model('product_warehouse_transfer')->transfer_add($post, $one);
            if (model('product_warehouse_transfer')->hasError()) {
                model('operate')->failure(model('product_warehouse_transfer')->getError());
                return $this->renderError(model('product_warehouse_transfer')->getError());
            }
            model('operate')->success('库存调拨');
            return $this->renderSuccess('库存调拨' , 'reload');
        } else {


            $this->assign('lists', model('product_inventory')->model_where()->where('a.id', $id)->find());
            $this->assign('warehouse', model('product_warehouse')->model_where()->where('pwu.u_id', UID)->select());


            return view();
        }
    }

    /**
     * @title 调拨查询
     */
    public function transfer_query() {


        if (!isset($_GET['timea']))
            $_GET['timea'] = date('Y-m-d', strtotime("-30 day"));
        if (!isset($_GET['timeb']))
            $_GET['timeb'] = date('Y-m-d');

        $this->assign('warehouse', model('product_warehouse')->model_where()->where('pwu.u_id', UID)->column('a.id,a.name'));
        $this->assign('category', model('product_category')->lists_select_tree());


        $count = model('product_warehouse_transfer')->model_where()->count('distinct a.id');
        $lists = model('product_warehouse_transfer')->model_where()->group('a.id')->paginate(input('get.page_size', 10), $count, ['query' => request()->get()]);

        $this->assign('count', $count);
        $this->assign('lists', $lists);
        $this->assign('pages', $lists->render());


        return view();
    }

    /**
     * @title 调拨撤销
     * @param type $id
     */
    public function transfer_undo($id) {


        empty($id) && exit();

        $result = model('product_warehouse_transfer')->transfer_undo($id);

        if (true === $result) {
            return ['code' => 1, 'msg' => 'success', 'data' => 1, 'url' => 'reload'];
        } else {
            return ['code' => 0, 'msg' => $result, 'data' => 1];
        }
    }

    /**
     * @title 报废窗口
     */
    public function scrapped_add($id) {


        empty($id) && exit();


        if (request()->isPost()) {

            $post = request()->post();


            $one = model('product_inventory')->where('id', $id)->find();

            if (empty($one))
                return $this->renderError('产品不存在');

            if (!isset($post['quantity']) || !is_numeric($post['quantity']) || $one['quantity'] < $post['quantity']) {
                return $this->renderError('没那么货报废');
            }


            model('product_scrapped')->scrapped_add($post, $one);
            if (model('product_scrapped')->hasError()) {
                model('operate')->failure(model('product_scrapped')->getError());
                return $this->renderError(model('product_scrapped')->getError());
            }
            model('operate')->success('报废产品');
            return $this->renderSuccess('报废成功', 'reload');
        } else {
            $this->assign('var', model('product_inventory')->model_where()->where('a.id', $id)->find());
            return view();
        }
    }

    /**
     * @title 报废查询
     */
    public function scrapped_query() {


        if (!isset($_GET['timea']))
            $_GET['timea'] = date('Y-m-d', strtotime("-30 day"));
        if (!isset($_GET['timeb']))
            $_GET['timeb'] = date('Y-m-d');

        $this->assign('warehouse', model('product_warehouse')->model_where()->where('pwu.u_id', UID)->column('a.id,a.name'));
        $this->assign('category', model('product_category')->lists_select_tree());

        $count = model('product_scrapped')->model_where()->count('distinct a.id');
        $lists = model('product_scrapped')->model_where()->group('a.id')->paginate(input('get.page_size', 10), $count, ['query' => request()->get()]);

        $this->assign('count', $count);
        $this->assign('lists', $lists);
        $this->assign('pages', $lists->render());


        return view();
    }

}
